<?php

namespace app\api\service;
use app\model\User;
use app\admin\model\Orders;
use think\Exception;
use think\Queue;


class PayService
{
    public $error_msg = '';
    private $orderID;
    private $orderNO;
    public $user_id = 0;
    public $money;
    public $pay_status; ///-1关闭 0表示直接成功 大于0 表示以该小金额

    function __construct($orderID,$user_id,$pay_status=0)
    {
        $this->user_id = $user_id;
        $this->orderID = $orderID;
        $this->pay_status = $pay_status;
        if(empty($pay_status))
            $this->pay_status = config('global.pay_status');
    }

    //验证订单、支付、改变状态
    public function pay()
    {
        $checkRes = $this->checkOrderValid();
        if($checkRes == false){
            return dataReturn(-1,$this->error_msg);
        }
        $order_money=intval(100*$this->money);
        $userModel = new User();
        $openid = $userModel->where('id',$this->user_id)->value('openid');
        $payconfigService = new PayConfig();
        $result = $payconfigService->play($order_money,$this->orderNO,'购买商品',$openid);//进行微信支付
        if($result == false){
            return dataReturn(-1,$payconfigService->error_msg);
        }
        $reData = json_decode($result,true);
        $reData['pay_status'] = $this->pay_status;
        $reData['order_no'] = $this->orderNO;
        return dataReturn(0,'success',$reData);
    }


    private function checkOrderValid()
    {
        $orderModel = new Orders();
        $order =$orderModel->where('id', $this->orderID)->find();
        if (!$order->count())
        {
            $this->error_msg = '订单不存在或已过期';
            return false;
//            throw new BaseException(['msg'=>'订单不存在或已过期']);
        }
        if ($this->user_id!=$order['user_id'])
        {
            $this->error_msg ='非法操作'.$this->user_id.'!='.$order['user_id'];
            return false;
        }
        //非待支付状态，则终止
        if ($order['status'] != $orderModel::STATUS_WAITPAY)
        {
            $this->error_msg = '订单已支付过啦';
            return false;
        }
        $this->orderNO = $order['order_no'];
        $this->money = $order['total_price']; //可能含有余额 用实际支付的
        //-1关闭 0表示直接成功 大于0 表示以该小金额
        if($this->pay_status > 0){
            $this->money = $this->pay_status;
        }
        return true;
    }

    //处理订单成功后的积分获取 消费记录 佣金收入
    //推荐人的佣金账单  优惠劵已使用  次数加加
    //库存 销量
    //paycate 余额支付的话  扣减余额  不是余额支付 不能扣减余额
    //订单完毕时候  处理一下 佣金的收入
    //用户的余额 是否扣减
    public function afterOrder(){
        try{
            $orderModel = new Orders();
            $orderData = $orderModel->find($this->orderID);

            if($orderData['status'] != $orderModel::STATUS_WAITPAY){
                return false;
            }

            $uid = $orderData['user_id'];
            $upOrder['status'] = $orderModel::STATUS_HASPAY;//支付成功
            $orderModel->where("id",$this->orderID)->update($upOrder);

            if(!empty($orderData['remark'])){
                //续费的业务
                $remarkArr = explode('<>',$orderData['remark']);
                $order_id = $remarkArr[1] ?? 0;
                if(!empty($order_id)){
                    $orderModel->where('id',$order_id)->update(['status'=>$orderModel::STATUS_HASFINISH]);
                }
            }else{
                //则 异步推送让云机自动安装
//                Queue::push('\app\job\InstallApp', ['instance_code'=>$orderData['instance_code'],'order_no'=>$orderData['order_no']]);
            }

            if($orderData['type'] == 2){
                db('cloudphone')->where('id',$orderData['phone_id'])->update(['is_use_allday'=>1]);
            }else{
                db('cloudphone')->where('id',$orderData['phone_id'])->update(['is_use_allday'=>-1]);
            }
        }catch (\Exception $e){
            $error = $e->getLine()."消息".$e->getMessage();
            trace_log("小程序回调afterOrder错误异常:".$error,'after_order_error');
        }
        return dataReturn(0,'success',['pay_status'=>$this->pay_status,'order_no'=>$this->orderNO]);
    }


    //计算推荐人的佣金
    public function countRelationYongjin($userInfo,$goods_price){
        $userModel = new User();
        $userPartnerModel = new UserPartner();

        $user_relation_id = $userInfo['user_relation_id'];
        if(empty($user_relation_id)){
            $yongjin_rate = 0;
            $yongjin_price = 0;
        }else{
            //找到推荐人
            $relationInfo = $userModel->find($user_relation_id);
            if(empty($relationInfo)){
                //用户不存在了
                $user_relation_id = 0;
                $yongjin_rate = 0;
                $yongjin_price = 0;
                return  compact('user_relation_id','yongjin_rate','yongjin_price');
            }


            if($relationInfo['is_disable'] == 1 || $relationInfo['is_delete'] == 1){
                $yongjin_rate = 0;
                $yongjin_price = 0;
                $user_relation_id = 0;
            }else{
                $tuiguang_id = $relationInfo['is_tuiguang'];
                $partnerInfo = $userPartnerModel->find($tuiguang_id);
                if(empty($partnerInfo)){
                    $yongjin_rate = 0;
                    $yongjin_price = 0;
                    return  compact('user_relation_id','yongjin_rate','yongjin_price');
                }

                $yongjin_rate = $partnerInfo['yongjin_rate'];
                if(empty($goods_price)){
                    $yongjin_price = 0;
                }else{
                    $yongjin_price = $goods_price*($yongjin_rate/100);
                   /* $relationInfo->save([
                        'yongjin_price' => round($relationInfo['yongjin_price']+$yongjin_price,2)
                    ]);*/
                }
            }
        }
        return  compact('user_relation_id','yongjin_rate','yongjin_price');
    }

}
